<template>
        <div id="main" class="main" :class="{'main-hide-text': hideMenuText}">

            <div class="IframeConnector" v-show="COTShow">
                <p>Oceana多媒体工具条</p>
                <span class="IframeConnectorSpan" @click = "narrowCOT" ><Icon type="arrow-shrink" style="font-size: 20px"></Icon></span>
                <iframe name="myframe" id="Iframe" frameborder="0" HEIGHT="100%" WIDTH="100%" SCROLLING="NO" marginheight=0 marginwidth=0 src="https://bjebcedp16-sm100.aps.avaya.com/services/sunrise-2-0-0-oc/">
                </iframe>
            </div>
            <div class="IframeConnectorHide" v-show="COTHide">
                <p>Oceana多媒体工具条</p>
                <span class="IframeConnectorSpanHide" @click = "narrowCOTHide" ><Icon type="arrow-expand" style="font-size: 20px"></Icon></span>
            </div>
            <div class="sidebar-menu-con" :style="{width: hideMenuText?'60px':'150px', overflow: hideMenuText ? 'visible' : 'auto', background: $store.state.theme === 'dark'?'#495060':'#495060'}">
                <div class="header-avator-con" v-if="!hideMenuText">
                  <Avatar icon="person" size="large" />
                  <span class="username">{{loginUserInfo.curHandlerName}}</span>
                    <!-- <span><Icon type="checkmark-circled" color="#fff"></Icon> 在线</span> -->
                </div>

                <div class="header-avator-con" v-else>
                    <span class="username">{{loginUserInfo.curHandlerName}}</span>
                    <!--<span><Icon type="checkmark-circled" color="#fff"></Icon></span>-->
                </div>
                <sidebar-menu v-if="!hideMenuText" :menuList="menuList" :iconSize="14"></sidebar-menu>
                <sidebar-menu-shrink  v-else :menuList="menuList"/>
              <!--&lt;!&ndash;退出弹出框&ndash;&gt;-->
              <div v-on:click='logOutShow = logOutShow == true?false:true' class="turnQuite" style="cursor: pointer"  >
                <Icon type="power"  style="font-size: 16px;color: #FFFFFF;"></Icon>
                <p>注销</p>
              </div>
              <div class="logOutDialogCon" v-show="logOutShow" style="background: rgb(73, 80, 96);width: 100%;height: 100px">
                <div class="logOutDialog"  @mouseover="logOutShow=true" @mouseout="logOutShow=false">
                  <span @click="logOutOk">确定</span>
                  <!--<span  @click="logOutCal">取消</span>-->
                </div>
              </div>

            </div>
            <div class="main-header-con" :style="{paddingLeft: hideMenuText?'60px':'150px'}">
                <div class="main-header">
                    <div class="navicon-con">
                        <Button :style="{transform: 'rotateZ(' + (this.hideMenuText ? '-180' : '0') + 'deg)'}" type="text" @click="toggleClick">
                            <!--<Icon type="navicon" size="32"></Icon>-->
                          <Icon type="chevron-left" size="25"></Icon>
                        </Button>

                    </div>
                    <!--<div class="Iframe" >-->
                       <!--<iframe name="myframe" id="Iframe" frameborder="0" HEIGHT="100%" WIDTH="100%" SCROLLING="NO" marginheight=0 marginwidth=0 src="">-->
                       <!--</iframe>-->
                    <!--</div>-->
                    <div class="header-avator-con">
                       <div @click="showMessage" class="message-con">
                            <Tooltip :content="appointCount> 0 ? '有' +appointCount + '条预约回拨' : '无预约回拨'" placement="bottom">
                                <Badge :count="appointCount"  dot>
                                    <Icon type="ios-bell" :size="22" color="#495060"></Icon>
                                </Badge>
                            </Tooltip>
                        </div>
                    </div>
                </div>
                <div slot="extra">
                    <marquee></marquee>
                </div>
                <div class="tags-con">
                    <tags-page-opened :pageTagsList="pageOpenedList"></tags-page-opened>
                </div>

                <!-- 軟電話彈出框 -->
                <softPhoneIframe ></softPhoneIframe>
            </div>
            <div class="single-page-con" :style="{paddingLeft: hideMenuText?'60px':'150px'}">

                <div class="single-page">
                    <keep-alive :exclude="cacheExcludeComponent"><router-view v-if="$route.meta.keepAlive"></router-view></keep-alive>
                    <router-view v-if="!$route.meta.keepAlive"></router-view>
                </div>
            </div>
        </div>
    </template>
<style>
    .main{
        position: relative;
    }
    .turnQuite {
        position: absolute;
        left: 0px;
        bottom: 10px;
        width: 100%;
        /*border: 1px solid #DDDDDD;*/
    }
    
    .turnQuite p {
        display: inline-block;
        font-size: 16px;
        color: #FFFFFF;
    }
    
    .logOutDialogCon {
        position: absolute;
        left: 0px;
        bottom: 50px;
        width: 100%;
        height: 30px;
        /*background-color: #808080;*/
        /*border: 1px solid #DDDDDD;*/
        z-index: 999;
    }
    
    .logOutDialog {
        position: absolute;
        left: 0px;
        bottom: 12px;
        line-height: 100%;
        width: 100%;
        height: 30px;
        /*background-color: #808080;*/
        /*border: 1px solid #DDDDDD;*/
        z-index: 999;
    }
    
    .logOutDialog span {
        height: 35px;
        line-height: 30px;
        cursor: pointer;
        display: block;
        padding: 3px 10px;
        /*margin: 10px 0px;*/
        /*text-align: left;*/
        color: #FFFFFF;
    }
    
    .logOutDialog span:hover {
        background-color: #fff;
        color: #1a1a1a;
    }
    
    .Iframe {
        float: left;
        height: 60px;
        width: 850px;
        margin-top: 8px;
        /*margin-left:80px;*/
        /*margin-right: 300px;*/
        z-index: 2;
        /*border: 1px solid #ffeecc*/
    }
    
    .soft-phone {
        overflow: hidden;
        height: 79px;
        width: 100%;
        min-width: 1300px;
        position: absolute;
        top: 0px;
        left: 180px;
        right: 0px;
        height: 79px;
        background-color: #e6eaf2;
        transition: all .28s ease-out;
    }
    
    .texSty {
        float: left;
    }
    .IframeConnector{
        position: absolute;
        right: 0px;
        top:0px;
        min-width: 400px;
        max-width: 600px;
        height: 100%;
        border: 1px solid #2d8cf0;
        background-color: #fff;
        z-index: 1010;
    }
    .IframeConnector p{
        display: block;
        float: left;
        margin-left: 30px;
        font-size: 20px;
    }
    .IframeConnectorSpan{
        float: right;
        margin-right:20px;
        cursor: pointer;
    }
    .IframeConnectorSpan:hover{
        color: #2d8cf0;
    }

    .IframeConnectorHide{
        position: absolute;
        right: 0px;
        bottom:0px;
        width: 300px;
        height: 30px;
        border: 1px solid #2d8cf0;
        border-top-left-radius: 20px;
        background-color: #fff;
        z-index: 1010;
    }
    .IframeConnectorHide p{
        display: block;
        float: left;
        margin-left: 30px;
        font-size: 20px;
    }
    .IframeConnectorSpanHide{
        float: right;
        margin-right:20px;
        cursor: pointer;
    }
    .IframeConnectorSpanHide:hover{
        color: #2d8cf0;
    }
</style>

<script scoped>
    import "assets/css/main.less";
    import jsCookie from 'js-cookie';
    import loginService from "service/loginService.js";




    import {
        mapGetters
    } from 'vuex'
    import sidebarMenu from 'components/sideBar/sidebarMenu.vue';
    import sidebarMenuShrink from 'components/sideBar/sidebarMenuShrink.vue'
    import breadcrumbNav from 'components/breadcrumbNav/breadcrumbNav.vue'
    import themeDropdownMenu from 'components/theme/themeDropdownMenu.vue';
    import marquee from 'components/marquee/marquee.vue';
    import tagsPageOpened from 'components/tagsPageOpened/tagsPageOpened.vue'
    import bookingList from 'components/voiceCall/bookingList.js';
    import softPhoneIframe from 'components/softPhoneIframe.vue';
    import * as configHost from 'service/config.js'
    import domAction from '@/libs/dom.js'

    export default {
        components: {
            sidebarMenu,
            sidebarMenuShrink,
            breadcrumbNav,
            themeDropdownMenu,
            marquee,
            tagsPageOpened,
            softPhoneIframe,

        },
        data() {
            return {
                currentPageName: '',
                hideMenuText: false,
                logOutShow: false, //退出显示框
                stompClient: {},
                interval: '',
                COTShow:true,
                COTHide:false

            };
        },
        computed: {
            ...mapGetters({
                menuList: 'menuList',
                pageOpenedList: 'pageOpenedList',
                loginUserInfo: 'loginUserInfo',
                appointList: 'appointList',
                reCallNum: 'reCallNum',
                cacheExcludeComponent: 'cacheExcludeComponent'
            }),
            appointCount() {
                let count = this.appointList.length > 0 ? this.appointList.length : '0'
                return count
            }

        },

        methods: {
            logOut() {
                this.logOutShow = true

            },
            //确定退出
            async logOutOk() {
                localStorage.removeItem("pageOpenedList");
                await loginService.logout({})
                jsCookie.set('sessId', '')
                this.$router.go(0)
                this.$router.push({
                    path: "/login"
                })

            },
            //取消退出
            logOutCal() {
                this.logOutShow = false
            },
            //设置iframe异步加载
            // setIframeSrc() {
            //     let s = this.baseIframeUrl;
            //     let iframe1 = document.getElementById('Iframe');
            //     if (-1 == navigator.userAgent.indexOf("MSIE")) {
            //         iframe1.src = s;
            //     } else {
            //         iframe1.location = s;
            //
            //     }
            //
            // },
            // Check for browser support of event handling capability
            //          asIframe(d){
            //            console.log(d);
            //            console.log($(d));
            //            console.log(createElement('iframe'));
            //            let iframe = $(d).push(createElement('iframe'));
            //            let doc = iframe.contentWindow.document;
            //            console.log(doc);
            //            // style the iframe with some CSS
            //            iframe.style.cssText ="position:absolute;width:200px;height:100px;left:0px;";
            //            doc.open().write(''<'body onload="'+ 'var d = document;d.getElementsByTagName(\'head\')[0].'+
            //              'appendChild(d.createElement(\'script\')).src'+'=\'\/path\/to\/file\'">');
            //            doc.close(); //iframe onload event happens
            //          },
            //        <iframe name="myframe" id="Iframe" frameborder="0" HEIGHT="100%" WIDTH="100%" SCROLLING="NO" marginheight=0 marginwidth=0 :src="baseIframeUrl">
            //      </iframe>
            //     (function(d) {
            //       var iframe = d.body.appendChild(d.createElement('iframe')),
            //         doc = iframe.contentWindow.document;
            //       // style the iframe with some CSS
            //       iframe.style.cssText ="position:absolute;width:200px;height:100px;left:0px;";
            //       doc.open().write('<body onload="'+
            //         'var d = document;d.getElementsByTagName(\'head\')[0].'+
            //         'appendChild(d.createElement(\'script\')).src'+'=\'\/path\/to\/file\'">');
            //       doc.close(); //iframe onload event happens
            //     })(document),

            toggleClick() {
                this.hideMenuText = !this.hideMenuText;
            },
            showMessage() {

                bookingList.showBookingList({
                    'loginUserId': this.loginUserInfo.userId,
                    "remove": bookingList.remove,
                    'setAppointRecallNo': this.setAppointRecallNo
                })
            },
            setAppointRecallNo(data) {

                let stuId = data.stuId,
                    stuName = data.stuName ? data.stuName : '',
                    telNo = data.telNo,
                    appointId = data.appointId


                this.$store.dispatch('removePageTags', {
                    'path': '/voicecall'
                })

                let updateTagObj = {
                    path: '/voicecall?studentId=' + stuId + '&appointId=' + appointId + '&from=appoint',
                    is_nav: false,
                    title: '预约外呼-' + stuName,
                    name: 'voicecall_index',
                    children: []
                }

                this.$store.dispatch('recordDetailPageTags', updateTagObj)


                this.$router.push({
                    path: 'voicecall',
                    query: {
                        'studentId': stuId,
                        'appointId': appointId,
                        'from': 'appoint'
                    }
                });
                this.$router.go(0)

                // this.$store.dispatch('setCacheExcludeComponentName', 'voiceCall') //预约外呼 跳转弹屏页面 清空记录

            },
            socketDescribe() {

                let vm = this
                if (this.loginUserInfo.userId) {
                    let socketApi = configHost.SOCKET_API
                    let ws = new SockJS(socketApi + '/pushman/endpoint-push-man')
                    let stompClient = Stomp.over(ws);
                    this.stompClient = stompClient
                    stompClient.heartbeat.outgoing = 0
                    stompClient.heartbeat.incoming = 0
                    stompClient.connect({}, function() {
                        stompClient.subscribe(
                            '/queue/message.' + vm.loginUserInfo.userId,
                            function(response) {
                                let body = JSON.parse(response.body)

                                if (body.type == 'APPOINTMENT') {

                                    bookingList.showBookingList({
                                        'appointId': body.id,
                                        'loginUserId': vm.loginUserInfo.userId,
                                        "remove": bookingList.remove,
                                        'setAppointRecallNo': vm.setAppointRecallNo
                                    })


                                }
                            }
                        )
                    }, {
                        'x-max-length': 1
                    });
                }
            },
            ping() {
                let vm = this

                this.stompClient.subscribe(
                    '/app/heartbreak/' + vm.loginUserInfo.userId,
                    function(response) {
                        // board.text(response.body);
                    }
                )
            },
          //登陆反回
          async login_goto(name, pwd) {
            let jsondata = await loginService.login_goto({
              'userId': name,
              'passwd': pwd,

            }, this.loginCallback)

            if (jsondata.message == '用户名或密码错误') {
              this.$Message.error('账号密码错误请重新登陆');
              this.loading2 = false;
            } else {
              localStorage.setItem('username', name);
              localStorage.setItem('userpwd', pwd);
              this.getStateHome(name);
              this.$store.dispatch('getRoleList', {
                'userId': name
              })
              localStorage.setItem('UserID', name);
              console.log(jsondata);
              console.log(jsondata.userId);
              localStorage.setItem('UserID', jsondata);
              this.$store.dispatch('setLoginUserInfo', {
                "userId": jsondata.userId, //登陆人ID
                "curHandlerGroupId": jsondata.skillCode, // 操作人所属组ID
                "curHandlerGroupName": jsondata.skillName, // 操作人所属组名字
                "curHandlerName": jsondata.userName, // 操作人（登陆人）名字
                "curHandlerId": jsondata.voiceAgentId // 操作人工号
              })
              // this.user_info();
              //                   sessionStorage.setItem('sessId',123)

              jsCookie.set('sessId', '111')
              //                   cookie.setItem('sunnyDayCookie',1)
            }
          },
          //获取用户列表
          async getStateHome(id) {
            let jsondata = await loginService.stateHome({
              userId: id
            });
            this.GROUP_USER = jsondata.roleCodeList;
            var that_ = this;
            if (that_.GROUP_USER.length > 0) {
              var flag_user;
              for (var i = 0; i < that_.GROUP_USER.length; i++) {
                if (that_.GROUP_USER[i].search("GROUP_MEMBER") != -1) {
                  // 组员
                  flag_user = true;
                  that_.$store.dispatch('updateMenulist', {
                    'userId': that_.formAgent.user
                  });
                  that_.$store.dispatch('getOpenedList');
                } else if (that_.GROUP_USER[i].search("GROUP_LEADER") != -1) {
                  // 组长
                  flag_user = true;
                  that_.$store.dispatch('updateMenulist', {
                    'userId': that_.formAgent.user
                  });
                  that_.$store.dispatch('getOpenedList');
                } else if (that_.GROUP_USER[i].search("GROUP_MANAGER") != -1) {
                  // 值班经理
                  flag_user = true;
                  that_.$store.dispatch('updateMenulist', {
                    'userId': that_.formAgent.user
                  });
                  that_.$store.dispatch('getOpenedList');
                }
              }
              if (!flag_user) {
                localStorage.removeItem("pageOpenedList");
                that_.$Message.info('当前用户没有坐席权限');
                that_.loading2 = false;
              } else {
                that_.$router.push({
                  path: "/home"
                });
              }
            } else {
              localStorage.removeItem("pageOpenedList");
              that_.$Message.info('当前用户没有坐席权限');
              that_.loading2 = false;
              // that_.$router.push({
              //     path: "/"
              // });

            }

          },
          narrowCOT(){
                this.COTShow = false;
                this.COTHide = true;
          },
          narrowCOTHide(){
                this.COTShow = true;
                this.COTHide = false;


          },
          //来电弹屏
          dcg_PopupScreen(data){
              console.log('执行了1')
            this.$router.push({
              path: '/addCallConfirm',
              query:{data}});
          },
          dcg_cannedData(data){
            console.log('执行了2')
            this.$router.push({
              path: '/addCallConfirm',
              query:{data}});
          }

        },
        watch: {
            loginUserInfo(newVal, oldVal) {
                //预约回拨数
                this.$store.dispatch('getAppointList', {
                    'userId': newVal.userId
                })
                this.$store.dispatch('getRoleList', {
                    'userId': this.loginUserInfo.userId
                })
                this.$store.dispatch('updateMenulist', {
                    'userId': this.loginUserInfo.userId
                });
                this.socketDescribe()
              console.log(this.loginUserInfo.userId);
              // console.log(this.appointList)
                // this.appointCount = this.appointList.length > 0 ? this.appointList.length : '0'
            },
            //          reCallNum(){
            //            console.log(this.reCallNum);
            //            if(this.reCallNum!=''){
            //                this.reCall(this.reCallNum)
            //              }
            //          }

        },
        created() {
            this.$store.dispatch('updateMenulist', {
                'userId': this.loginUserInfo.userId
            });
            // 显示打开的页面的列表
            this.$store.commit('getOpenedList');
            this.$store.dispatch('getLoginUserInfo')

            //calluserInfo
            this.$store.commit('getCalluserInfo')

            if (this.loginUserInfo.userId) {
                this.$store.dispatch('getAppointList', {
                    'userId': this.loginUserInfo.userId
                })
                this.$store.dispatch('getRoleList', {
                    'userId': this.loginUserInfo.userId
                })
            }


            // //设置来电人 信息
            // this.$store.dispatch('setCallUserInfo', {
            //     'telNo': '13378789393',
            //     'callID': '123456789'
            // })
            let vm = this
            eventBus.$on('refreshAppointCount', function() {
                    vm.$store.dispatch('getAppointList', {
                        'userId': vm.loginUserInfo.userId
                    })
                })
                //预约提醒
            this.socketDescribe()


            let body_height = domAction.getStyle(document.body, 'height')
            let _top = parseInt(body_height) / 2
            this.$Message.config({
                top: _top,
                duration: 1
            });

            this.interval = setInterval(this.ping, 10000)
        },
        destroyed() {
            clearInterval(this.interval)
        },
        mounted() {
            //          $('#Iframe').contents().find("#phone-dial-num").val(123412);
            //          console.log($('#Iframe').contents())
            //          console.log($('#Iframe').contents().find("#phone-dial-num"))
            //        this.asIframe(this.$refs.asIframe);
            // setTimeout(this.setIframeSrc, 5);
            let _this = this;
          _this.login_goto(localStorage.getItem('username'), localStorage.getItem('userpwd'))
          window.addEventListener("message", function(e){
            console.log(e.data);
            if(e.data.funcName=='dcg_PopupScreen'){
              console.log(1);
              _this.dcg_PopupScreen(e.data.funcData);
              // _this.$store.dispatch('setCallUserInfo', e.data.funcData)
            }else if(e.data.funcName=='dcg_cannedData'){
              console.log(2);
              _this.dcg_cannedData(e.data.funcData);
              // _this.$store.dispatch('setCallUserInfo', e.data.funcData)

            }

          })
          //          window.onload = function(){
            //            window.frames[0].postMessage(_this.reCallNum, '*');
            //          }

            //          console.log( document.getElementById('Iframe').contentWindow.document)

            //         document.getElementById('Iframe').contentWindow.document.getElementById('phone-dial-num').value=this.reCallNum

        }
    };
</script>